package com.cloud.common.bean;

import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.ListUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;

/**
 * 分页信息
 *
 * @author fengwenjin
 */
@Data
@NoArgsConstructor
public class PageInfo<T> {

    /**
     * 总记录数
     */
    private int total;

    /**
     * 页数
     */
    private int count;

    /**
     * 当前页
     */
    private int current;

    /**
     * 每页大小
     */
    private int size;

    /**
     * 每页数据
     */
    private List<T> rows = Collections.emptyList();

    public PageInfo(IPage<T> page) {
        rows = page.getRecords();
        size = (int) page.getSize();
        total = (int) page.getTotal();
        current = (int) page.getCurrent();
        count = (total + size - 1) / size;
    }

    public <RT> PageInfo<RT> build(List<RT> rows) {
        PageInfo<RT> pageInfo = new PageInfo<>();
        BeanUtils.copyProperties(this, pageInfo, "rows");
        pageInfo.setRows(rows);
        return pageInfo;
    }

    public static <T> PageInfo slice(List<T> list, int pageNo, int pageSize) {
        PageInfo<T> pageInfo = new PageInfo<>();
        if (CollectionUtils.isEmpty(list)) {
            return pageInfo;
        }
        List<List<T>> partitionList = ListUtils.partition(list, pageSize);
        int pageCount = partitionList.size();

        pageNo = pageNo > pageCount ? pageCount : pageNo;
        pageNo = pageNo == 0 ? 1 : pageNo;

        pageInfo.setCurrent(pageNo);
        pageInfo.setSize(pageSize);
        pageInfo.setCount(pageCount);
        pageInfo.setTotal(list.size());
        pageInfo.setRows(partitionList.get(pageNo - 1));
        return pageInfo;
    }
}